import React, { Component } from 'react'
import {
  View, TextInput, StyleSheet, Text, Image, SafeAreaView, Navigator, TouchableOpacity, Platform
} from 'react-native'
import { LOGIN_BY_USERPWD, LOGIN_VERIFICATION_CODE, LOGIN_REGISTER, POST_APPPOSITION_ADD } from '../../public/WebApi/apiList';
import fetchWebApi from '../../public/WebApi/fetchBase';
import { Constant } from '../../public/js/constant';
import AsyncStorage from '@react-native-community/async-storage';
import { GetLocation } from '../../utils/GetLocation'
import getStorageValue from '../../utils/getStorageValue';
import { setStorageValue } from '../../utils/storage';
import { Friend, Group } from '../../types/redux';
import fetch from '../../utils/fetch';
import platform from '../../utils/platform';
import action from '../../state/action';
import { Actions } from 'react-native-router-flux';
// 弹窗提示
import Layer from '../../utils/Layer';
import { PermissionsAndroid } from 'react-native';
export default class Logins extends Component {
  constructor(props) {
    super(props)
    this.state = {
      UserName: "",//用户名
      password: "",//密码
      PasswordAgain: "",//验证密码
      phoneNumber: '',//手机号码
      VerificationCodes: "",//验证码
      Loginjudgment: false,
      regular: false,
      //验证码
      VerificationCode: [],
      time: 0,
      MainTime: '',
      MainTimeTitle: '获取验证码',
      timeId: '',
      latitude: 500,
      longitude: 500,
      positions: ''
    }


  }

  async componentDidMount() {
    if (Platform.OS === 'android') {
      await this.requestLocationPermission();
      this.getUserLocaltion();
    } else {
      Geolocation.requestAuthorization()
    }
  }
  async getUserLocaltion() {
    await GetLocation();
    setTimeout(() => {
      if (Object.keys(GetLocation()._55).length > 0) {
        this.setState({
          latitude: GetLocation()._55.latitude,
          longitude: GetLocation()._55.longitude,
          positions: GetLocation()._55.positions.aois[0].name
        })
      } else {
        alert("获取地址失败，请重新进入系统！")
      }
    }, 3000)
  }
  componentDidUpdate = () => {
  }

  //验证码
  async VerificationCode() {
    const res = await fetchWebApi(LOGIN_VERIFICATION_CODE, { phone: this.state.phoneNumber }, 'POST');
    if (res.status == 200) {
      // console.log(this.state.DATAS)
      // this.setState({
      //   VerificationCode: res.data
      // })


    } else {
      Layer.showMsg(res.msg);
    }
  }
  //地理位置权限
  async requestLocationPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          //第一次请求拒绝后提示用户你为什么要这个权限
          'title': '我要地址查询权限',
          'message': '没权限我不能工作，同意就好了'
        }
      )

      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        // alert("你已获取了地址查询权限")
      } else {
        // alert("获取地址查询失败")
        this.requestLocationPermission()
      }
    } catch (err) {
      alert(err.toString())
    }
  }

  // async Register() {
  //   // if (this.state.password === this.state.PasswordAgain) {
  //   const res = await fetchWebApi(POST_APPPOSITION_ADD, {

  //   }, 'POST');
  //   // console.log("########## getUserMaillist########");
  //   // console.log(res);
  //   if (res.status == 200) {
  //     handleChange()

  //     await AsyncStorage.setItem(Constant.TOKEN, res.data.token);
  //     // console.log(this.state.DATAS)
  //     // this.setState({
  //     //   VerificationCode: res.data
  //     // })
  //     Layer.showMsg(res.msg);
  //     this.props.navigation.push('MainStack')
  //   } else {
  //     Layer.showMsg(res.msg);
  //   }
  //   // } else {
  //   //   Layer.showMsg('密码不一致');
  //   // }

  // }
  //地理
  async dili() {
    const {
      latitude,
      longitude,
      positions
    } = this.state
    if (latitude == 500 && longitude == 500) {
      console.log(latitude);
      return;
    } else {
      const res = await fetchWebApi(POST_APPPOSITION_ADD,
        {
          token: await getStorageValue(Constant.TOKEN),
          lat: latitude,
          lon: longitude,
          flag: "2",
          placeName: positions
        }, 'POST');
    }
    if (res.status == 200) {
      // console.log(this.state.DATAS)
      // this.setState({
      //   VerificationCode: res.data
      // })


    } else {
      Layer.showMsg(res.msg);
    }
  }

  //注册
  async Register() {
    if (this.state.password === this.state.PasswordAgain) {
      const res = await fetchWebApi(LOGIN_REGISTER, { nickName: this.state.UserName, password: this.state.password, account: this.state.phoneNumber, captcha: this.state.VerificationCodes }, 'POST');
      // console.log("########## getUserMaillist########");
      // console.log(res);
      if (res.status == 200) {


        await AsyncStorage.setItem(Constant.TOKEN, res.data.token);
        const [err, res2] = await fetch(
          'register',
          {
            username: this.state.phoneNumber,
            password: this.state.password,
            ...platform,
          },
        );
        console.log('###############');
        console.log(res2);
        if (!err) {
          // Toast.show({
          //   text: '创建成功',
          //   type: 'success',
          // });

          const user = res2;
          action.setUser(user);
          console.log(user);

          const linkmanIds = [
            ...user.groups.map((g: Group) => g._id),
            ...user.friends.map((f: Friend) => f._id),
          ];
          console.log(linkmanIds);
          console.log('11111111');
          Actions.maillist()
          const [err2, linkmans] = await fetch('getLinkmansLastMessagesV2', {
            linkmans: linkmanIds,
          });
          if (!err2) {
            action.setLinkmansLastMessages(linkmans);
          }

          // Layer.showMsg(res.msg);
          await setStorageValue('token', res2.token);
        }

        // console.log(this.state.DATAS)
        // this.setState({
        //   VerificationCode: res.data
        // })
        this.dili()
        Layer.showMsg(res.msg);
        this.props.navigation.push('MainStack')
      } else {
        Layer.showMsg(res.msg);
      }
    } else {
      Layer.showMsg('密码不一致');
    }

  }

  phoneNumber(text) {
    this.setState({
      phoneNumber: text
    })
  };
  UserName(text) {

    this.setState({
      UserName: text
    })
  }
  password(text) {

    this.setState({
      password: text
    })
  }
  PasswordAgain(text) {

    this.setState({
      PasswordAgain: text
    })
  }
  //
  VerificationCodes(text) {

    this.setState({
      VerificationCodes: text
    })
  }
  //验证码
  time = () => {
    this.VerificationCode()
    if (this.state.MainTime <= 0) {


      this.setState({
        MainTime: 60,
        MainTimeTitle: ''
      });
      this.bb = setInterval(() => {
        var aa = this.state.MainTime - 1;
        if (aa === 0) {
          clearInterval(this.bb);
          this.setState({
            MainTime: '',
            MainTimeTitle: '重新获取'
          })
        } else {
          this.setState({
            MainTime: aa,
            MainTimeTitle: ''
          })
        }
      }, 1000)
      this.setState({
        timeId: this.bb
      });
    }
  }
  onClick() {

  }
  Agreementcheck() {
    const {
      Loginjudgment
    } = this.state
    if (Loginjudgment) {
      return (
        <Image style={{ width: 15, height: 15, marginRight: 10 }} source={require('../../assets/images/search/Frameps.png')} ></Image>
      )
    } else {
      return (
        <Image source={require('../../assets/images/search/Ellipsess.png')} style={{ width: 15, height: 15, marginRight: 10 }}></Image>
      )
    }
  }

  render() {

    return (
      <SafeAreaView style={styles.container}>

        <View style={styles.containers} >
          <Text style={styles.Contenttext}>手机号快捷注册</Text>
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.UserName(text)}
            value={this.state.UserName}
            placeholder={"请输入你的名称"}
          />
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.password(text)}
            value={this.state.password}
            placeholder={"请输入您密码"}
          />
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.PasswordAgain(text)}
            value={this.state.PasswordAgain}
            placeholder={"请再次输入密码"}
          />
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.phoneNumber(text)}
            value={this.state.phoneNumber}
            keyboardType={'numeric'}
            placeholder={"请输入您的手机号码"}
          />
        </View>
        <View style={styles.inputSearchBox}>
          <TextInput
            style={styles.inputSearch}
            onChangeText={text => this.VerificationCodes(text)}
            value={this.state.VerificationCodes}
            keyboardType={'numeric'}
            placeholder={"输入验证码"}
          />
          <Text style={styles.VerificationCode} onPress={() => { this.time() }}>{this.state.MainTime}{this.state.MainTimeTitle}</Text>
        </View>
        <View style={styles.middle}>
          <TouchableOpacity style={{ flexDirection: "row", alignItems: 'center' }} onPress={() => { this.setState({ Loginjudgment: !this.state.Loginjudgment }) }} >
            {this.Agreementcheck()}
            <Text>我已阅读</Text>
          </TouchableOpacity>
          <Text style={styles.colors}>《用户协议》</Text>
          <Text>和</Text>
          <Text style={styles.colors}>《平台协议》</Text>
        </View>
        <TouchableOpacity style={styles.tail} onPress={() => { this.Register() }} >
          <Text style={styles.Login}>注册</Text>
        </TouchableOpacity>
        <View style={styles.tails}>
          <Text style={styles.Tailcolor} onPress={() => { this.props.navigation.push('Accountlogin') }} >账号密码登录  </Text>
          <Text style={styles.Tailcolor}>收不到到验证码</Text>
        </View>
      </SafeAreaView >
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingLeft: 40,
    paddingRight: 40,
    display: 'flex',
    backgroundColor: 'white'
  },
  layer: {
    display: 'flex',
    justifyContent: 'space-around'
    , alignItems: 'center',
    flexDirection: 'row',
    marginTop: 120

  },
  Textred: {
    color: 'white'
  },
  inputSearchBox: {
    justifyContent: "center",
    height: 40,
    width: "100%",
    backgroundColor: 'rgba(232, 236, 240, 0.5)',
    marginTop: 25,
    borderRadius: 50,
  },
  inputSearch: {

    paddingLeft: 20,
    fontSize: 14,
    color: 'rgba(0, 0, 0, 0.31)'
  },
  containers: {
    marginTop: '25%',
    marginBottom: "8%"
  },
  move: {
    marginLeft: '8%'
  },
  Contenttext: {
    fontSize: 24,
    color: '#000000',
    fontWeight: 'bold',
  },
  Contenttexts: {
    fontSize: 13,
    color: 'rgba(0, 0, 0, 0.56)',
    marginLeft: 45,
    marginTop: 5,
    fontWeight: 'bold'
  },
  VerificationCode: {
    color: '#4C6BDC',
    position: 'absolute',
    right: "10%",
    fontSize: 12,
  },
  colors: {
    color: '#4C6BDC'
  },
  Login: {
    fontSize: 18,
    color: '#FFFFFF'
  },
  middle: {
    flexDirection: 'row',
    alignItems: "center",
    marginTop: 20,
  },
  tail: {
    width: '100%',
    marginTop: 30,
    justifyContent: "center",
    alignItems: 'center',
    backgroundColor: '#1890FF',
    height: 40,
    borderRadius: 50,
  },
  tails: {
    marginTop: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  Tailcolor: {
    fontSize: 12,
    color: 'rgba(0, 0, 0, 0.5)'
  },
  Agreementpicture: {
    justifyContent: "center",
    alignItems: "center",
    width: 16, height: 16, backgroundColor: "#1890FF", borderRadius: 50, marginRight: 10
  }

})